import { loginNestedAppForPhone } from '@/services/api/api-login';
import { setToken } from '@/utils/token';
import { Spin } from 'antd';
import React, { useEffect } from 'react';
import { history, useLocation, useModel } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const location = useLocation();

  const parse = (str = window.location.search) => {
    const reg = /([^?&=]+)=([^&]+)/g; // 分组捕获 两个子组
    const params = {};
    str.replace(reg, (_, k, v) => (params[k] = v));
    return params;
  };

  /** 此方法会跳转到 redirect 参数所在的位置 */
  const goto = () => {
    if (!history) return;

    const { phone, route } = parse(location.search) as { phone: string; route: string };

    console.log('==========', phone, route);

    loginNestedAppForPhone({ phone }).then(async ({ code, data }) => {
      if (code === 0) {
        setToken(data.satoken);
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
          setInitialState({
            ...initialState,
            currentUser: userInfo,
          });
          setTimeout(() => {
            if (history.replaceState) {
              history.replaceState(null, document.title, route);
              history.go(0);
            } else {
              history.replace(route);
            }
            // history.replace(route);
          }, 100);
        }
      }
    });
  };

  useEffect(() => {
    goto();
  }, []);

  return (
    <div
      style={{
        textAlign: 'center',
        marginTop: 20,
        marginBottom: 20,
      }}
    >
      <Spin size="large" />
    </div>
  );
};
